package amartin47;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class Editor extends JFrame
{
	JTextArea lyricsTextBox;
	JButton updateButton, serverButton, folderButton;
	JList songs;
	PageChooser chooser;
	boolean serverOn = false;
	LyricsServer server;
	File lyricsDir;
	
	public Editor()
	{
		//Set up layout
		FlowLayout layout = new FlowLayout();
		layout.setAlignment(FlowLayout.LEADING);
		this.setLayout(layout);
		
		//Set up components
		lyricsTextBox = new JTextArea();
		updateButton = new JButton("Update");
		serverButton = new JButton("Server (off)");
		folderButton = new JButton("Folder...");
		chooser = new PageChooser();
		songs = new JList(new String[0]);
		updateButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent arg0) {
				updateSlides();
			}
		});
		serverButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent arg0) {
				serverChange();
			}
		});
		folderButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent arg0) {
			    int result;
			    JFileChooser chooser;
			    
			    chooser = new JFileChooser(); 
			    chooser.setCurrentDirectory(new java.io.File("."));
			    chooser.setDialogTitle("Choose a folder");
			    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			    //
			    // disable the "All files" option.
			    //
			    chooser.setAcceptAllFileFilterUsed(false);
			    //    
			    if (chooser.showOpenDialog(Editor.this) == JFileChooser.APPROVE_OPTION) { 
			    	lyricsDir = chooser.getSelectedFile();
			    	String[] files = lyricsDir.list();
			    	songs.setListData(files);
			      }
			    else {
			      //System.out.println("No Selection ");
			      }
			     }
			
		});
		songs.addListSelectionListener(new ListSelectionListener() {
			
			@Override
			public void valueChanged(ListSelectionEvent e) {
				String path = lyricsDir.toString() + File.separatorChar + songs.getSelectedValue();
				try {
					BufferedReader br = new BufferedReader(new FileReader(path));
					String strLine;
					StringBuilder build = new StringBuilder();
					while((strLine = br.readLine()) != null) 
					{
						build.append(strLine);
						build.append('\n');
					}
					br.close();
					lyricsTextBox.setText(build.toString());
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		});
		
		//lyricsTextBox.setPreferredSize(new Dimension(300,300));
		JPanel leftSide = new JPanel();
		leftSide.setLayout(new BoxLayout(leftSide, BoxLayout.PAGE_AXIS));
		JScrollPane scrollPane = new JScrollPane(lyricsTextBox);
		scrollPane.setPreferredSize(new Dimension(300,300));
		JScrollPane scrollPaneSongs = new JScrollPane(songs);
		scrollPane.setPreferredSize(new Dimension(300,150));
		
		leftSide.add(serverButton);
		leftSide.add(scrollPane);
		leftSide.add(updateButton);
		leftSide.add(folderButton);
		leftSide.add(scrollPaneSongs);
		//chooser.setPreferredSize(new Dimension(200,200));
		//chooser.setMinimumSize(new Dimension(50,50));
		
		this.addWindowListener(new WindowAdapter() {
		      public void windowClosing(WindowEvent e) {
		    	  if(server != null)
		    	  {
					server.stopServer = true;
					server.close();
		    	  }
		        }
		      });
		
		//Add stuff
		this.add(leftSide);
		this.add(chooser);
		
		//Final things
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setMinimumSize(new Dimension(1000, 480));
	}
	
	private void serverChange()
	{
		serverOn = !serverOn;
		if(serverOn)
		{
			this.server = new LyricsServer(this.chooser);
			this.serverButton.setText("Server (on)");
		}
		else
		{
			this.server.stopServer = true;
			this.server.close();
			this.serverButton.setText("Server (off)");
		}
	}
	
	private void updateSlides()
	{
		String text = lyricsTextBox.getText();
		String[] split = text.split("\n\n");
		List<Slide> slides = new ArrayList<Slide>();
		int i = 0;
		
		for (String verse : split) {
			if(!verse.isEmpty())
			{
				Slide s = new Slide();
				while(verse.startsWith("\n"))
					verse = verse.substring(1);
				while(verse.endsWith("\n"))
					verse = verse.substring(0, verse.length() - 1);
				String[] lines = verse.split("\n");
				if(lines.length > 0 && lines[0].startsWith("~~~"))
				{
					s.title = lines[0].substring(3);
					verse = "";
					for(int j = 1; j < lines.length; j++)
					{
						verse += lines[j];
						if(j != lines.length - 1)
							verse += "\n";
					}
				}
				else
				{
					i++;
					s.title = "Slide " + i;
				}
				s.lyrics = verse;
				slides.add(s);
				
			}
		}
		
		chooser.setSlides(slides);
	}
	
	public static void main(String[] args)
	{
		Editor editor = new Editor();
		editor.setSize(600, 600);
		editor.setVisible(true);
	}
}

